<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/13
 * Time: 15:43
 */

namespace app\common\behaviour;


use think\Env;
use think\Request;

class AppInit
{
    private $allowOrigins = null;

    /**
     * @return array|null
     */
    public function getAllowOrigins()
    {
        if (is_null($this->allowOrigins)) {
            $allowOrigins = Env::get('server.AccessAllowOrigin');
            $this->allowOrigins = array_filter(explode(',', $allowOrigins));
        }
        return $this->allowOrigins;
    }

    private function checkOrigin($domain) {
        $origins = $this->getAllowOrigins();
        if (is_array($origins) && count($origins)>0) {
            return in_array($domain, $this->getAllowOrigins());
        } else {
            return $domain;
        }
    }

    public function run(& $params) {

        /**
         * 1、设置跨域信息头
         * 2、响应预检请求<OPTIONS>
         *
         *
         */
        $request = Request::instance();
        $domain = $request->header('Origin','*');
        if ($this->checkOrigin($domain) == false) {
            $domain = '*';
        }
        header('Access-Control-Allow-Origin: '.$domain);
        header('Access-Control-Allow-Headers: appid, appsecret, uid, token, version, content-type');
        header('Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,PATCH,DELETE');
        header('Access-Control-Allow-Credentials: true');

        if ($request->isOptions()) {
            http_response_code(204);
            die;
        }

    }
}